using System;
using Glue.Internals.Nulls;
using System.Collections.Generic;

namespace Glue.Internals
{
    internal class CreatorContainer
    {
        private readonly Dictionary<Type,Func<object,object>> creators = new Dictionary<Type, Func<object, object>>();
        public void Add(Type createsObjectsOfThisType, Func<object, object> creator)
        {
            creators.Add(createsObjectsOfThisType,creator);
        }

        public Func<object ,object> Get(Type type)
        {
            if (!Contains(type)) throw new GlueException("System error: Asked for a creator that does not exist. Please contact the developer of Glue.");
            return creators[type];
        }

        public bool Contains(Type type)
        {
            if (creators.ContainsKey(type)) return true;

            var constructorInfo = type.GetConstructor(new Type[0]).AsMaybe();
            if (!constructorInfo.HasValue()) return false;
            
            creators.Add(type, x => constructorInfo.GetValue().Invoke(new object[0]));
            return true;
        }
    }
}